import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/layout/MainLayout.vue'),
      redirect: '/dashboard/overview', //  重定向到第一个子路由
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          meta: { title: '仪表盘', icon: 'Odometer' },
          children: [
            {
              path: 'overview',
              name: 'Overview',
              component: () => import('@/views/dashboard/OverviewPage.vue'),
              meta: { title: '实时概览' }
            }
            // {
            //   path: 'analysis',
            //   name: 'Analysis',
            //   component: () => import('@/views/dashboard/AnalysisPage.vue'),
            //   meta: { title: '数据分析' }
            // }
          ]
        },
        {
          path: 'emergency',
          name: 'Emergency',
          meta: { title: '警情管理', icon: 'Warning' },
          redirect: '/emergency/list', // 添加重定向到警情列表
          children: [
            // 添加子路由
            {
              path: 'list',
              name: 'AlarmList',
              component: () => import('@/views/emergency/AlarmList.vue'),
              meta: { title: '警情列表' }
            },
            {
              path: 'statistics',
              name: 'CategoryStatistics',
              component: () => import('@/views/emergency/CategoryStatistics.vue'),
              meta: { title: '警情分类统计' }
            },
            {
              path: 'assign',
              name: 'AlertAssign',
              component: () => import('@/views/emergency/AlertAssign.vue'),
              meta: { title: '警情分配', hideInMenu: true }
            }
            // {
            //   path: 'records',
            //   name: 'RecordQuery',
            //   component: () => import('@/views/emergency/RecordQuery.vue'),
            //   meta: { title: '处理记录查询' }
            // }
          ]
        },
        {
          path: 'robot',
          name: 'Robot',
          // 移除了直接的component配置
          meta: { title: '机器人管理', icon: 'Robot' },
          redirect: '/robot/monitor', // 添加重定向到监控页面
          children: [
            {
              path: 'monitor',
              name: 'RobotMonitor',
              component: () => import('@/views/robot/MonitorPage.vue'),
              meta: { title: '状态监控' }
            },
            // {
            //   path: 'assignment',
            //   name: 'RobotAssignment',
            //   component: () => import('@/views/robot/AssignmentPage.vue'),
            //   meta: { title: '分配管理' }
            // },
            // {
            //   path: 'maintenance',
            //   name: 'RobotMaintenance',
            //   component: () => import('@/views/robot/MaintenancePage.vue'),
            //   meta: { title: '维护记录' }
            // },
            {
              path: 'video',
              name: 'VideoOnline',
              component: () => import('@/views/robot/VideoOnline.vue'),
              meta: { title: '实时监控', hideInMenu: true }
            }
          ]
        },
        // {
        //   path: 'data',
        //   name: 'Data',
        //   // 移除原来的component配置
        //   meta: { title: '数据中心', icon: 'DataAnalysis' },
        //   redirect: '/data/history', // 重定向到历史数据查询
        //   children: [
        //     {
        //       path: 'history',
        //       name: 'HistoryData',
        //       component: () => import('@/views/data/HistoryDataPage.vue'),
        //       meta: { title: '历史数据查询' }
        //     },
        //     {
        //       path: 'report',
        //       name: 'ReportGeneration',
        //       component: () => import('@/views/data/ReportPage.vue'),
        //       meta: { title: '分析报告生成' }
        //     },
        //     {
        //       path: 'anomaly',
        //       name: 'AnomalyRecord',
        //       component: () => import('@/views/data/AnomalyPage.vue'),
        //       meta: { title: '异常事件记录' }
        //     },
        //     {
        //       path: 'trend',
        //       name: 'TrendAnalysis',
        //       component: () => import('@/views/data/TrendPage.vue'),
        //       meta: { title: '趋势分析图表' }
        //     }
        //   ]
        // },
        {
          path: 'system',
          name: 'System',
          meta: { title: '个人中心', icon: 'Setting' },
          redirect: '/system/users',
          children: [
            {
              path: 'users',
              name: 'UserManagement',
              component: () => import('@/views/system/UserManagement.vue'),
              meta: { title: '用户管理' }
            }
            // {
            //   path: 'config',
            //   name: 'SystemConfig',
            //   component: () => import('@/views/system/SystemConfig.vue'),
            //   meta: { title: '系统配置' }
            // },
            // {
            //   path: 'logs',
            //   name: 'SystemLogs',
            //   component: () => import('@/views/system/SystemLogs.vue'),
            //   meta: { title: '系统日志' }
            // }
          ]
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue'),
      meta: { hidden: true }
    },
    {
      path: '/intro',
      component: () => import('@/views/introduction/IntroductionPage.vue'),
      meta: { hidden: true }
    }
  ]
})

// 安全地获取用户token
const getToken = () => {
  const userStore = useUserStore()
  return userStore?.token || null
}

// 路由守卫
router.beforeEach((to, from) => {
  // 定义不需要验证token的白名单路由
  const whiteList = ['/login', '/intro']

  // 如果目标路由在白名单中，直接放行
  if (whiteList.includes(to.path)) {
    return true
  }

  // 获取token
  const token = getToken()

  // 如果没有token且不在白名单中，跳转到登录页
  if (!token) {
    return {
      path: '/intro',
      query: {
        redirect: to.fullPath // 保存原本要去的路径
      }
    }
  }

  // 有token，如果要去登录页，重定向到首页（可选）
  if (whiteList.includes(to.path) && token) {
    return { path: '/' }
  }

  // 其他情况放行
  return true
})

// 路由错误处理
router.onError((error) => {
  console.error('Router error:', error)
})

export default router
